package com.example.service.impl;


import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URISyntaxException;

@Service
public class GetRecommend {

    public String requestByGetMethod(String id) throws URISyntaxException {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "http://127.0.0.1:5000/recommend";
        URIBuilder uriBuilder = new URIBuilder(url);
        uriBuilder.setParameter("id", id);
        StringBuilder entityStringBuilder = null;
        try {
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            RequestConfig config = RequestConfig.custom().setConnectTimeout(3000)  //创建链接的最长时间
                    .setConnectionRequestTimeout(500)  //从连接池中获取到链接的最长时间
                    .setSocketTimeout(40 * 1000)  //数据传输的最长时间
                    .build();
            httpGet.setConfig(config);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpGet);
            try {
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
                    result=result.replace("\n", "").replace(" ","");
                    System.out.println(result);

                }
//                HttpEntity entity = httpResponse.getEntity();
//                entityStringBuilder = new StringBuilder();
//                if (null != entity) {
//                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);
//                    String line = null;
//                    while ((line = bufferedReader.readLine()) != null) {
//                        entityStringBuilder.append(line + "/n");
//                    }
//                }
            } finally {
                httpResponse.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String args[]) {

        GetRecommend httpClientUtil = new GetRecommend();
        String res = null;
        try {
            res = httpClientUtil.requestByGetMethod("4779").split("/n")[0];

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
